import datetime
from django.conf import settings
from django.shortcuts import render,redirect,HttpResponse
from django.utils.deprecation import MiddlewareMixin
from web import models
'''登录验证中间件'''

class Tracer(object):
    def __init__(self):
        self.user = None
        self.price_policy = None
        self.project = None

class AuthMiddleware(MiddlewareMixin):
    def process_request(self,request):
        print("*************************************请求开始**************************************>>>>>>",request.path_info)
        request.tracer  = Tracer()
        info_dict = request.session.get("info","")
        if info_dict:
            user_id = info_dict["user_id"]
            user_object = models.UserInfo.objects.filter(id=user_id).first()
            request.tracer.user = user_object
        '''排除登录页面、验证码、手机短信登录、获取手机短信、首页、注册页'''
        if request.path_info in settings.WHITE_URL_LIST:
            return
        # 检查用户是否已登录，已登录继续往后走；未登录则返回登录页面。
        if not request.tracer.user:
            return redirect('/login/')
        # info_dict = request.session.get("info")
        if info_dict:
            current_time = datetime.datetime.now()
            # user_object = models.UserInfo.objects.filter(id=info_dict['user_id']).first()
            # request.tracer = user_object
            """ 获取用户额度根据交易记录表查找当前用户最后一条已支付的交易记录 """
            # orderinfo = models.OrderInfo.objects.filter(create_user=user_object,status=2).order_by("-id").first()
            orderinfo = models.OrderInfo.objects.filter(create_user_id=info_dict['user_id'],status=2).order_by("-id").first()
            """ 判断一下是否已过期 """
            if orderinfo.end_time and orderinfo.end_time<current_time:
                # 如果已经过期，那么就获取默认的免费版价格策略
                orderinfo = models.OrderInfo.objects.filter(create_user=info_dict['user_id'], status=2,price__category=1).first()
            request.tracer.user = orderinfo.create_user
            request.tracer.price_policy = orderinfo.price
            # print("****用户登录信息session****")
            return
        # return redirect("/login/")
        # return "999"
    def process_response(self,request,response):
        # info_dict = request.session.get("info")
        # if not info_dict:
        #     print("auth中间件---》》》","****响应结束，检测到用户未登录****")
        # else:
        #     print("auth中间件---》》》",f"****响应结束，用户{info_dict['user_name']}已登录****")
        print("*********************************************响应结束******************************", id(request))  # 在视图之后
        return response
    def process_view(self,request,view,args,kwargs):
        # 判断url是否manage开头，如果是则判断项目是否我创建的 或参与的
        if not request.path_info.startswith("/manage/"):
            # url不是manage开头，直接返回不进行下面判断
            return
        project_id = kwargs.get("project_id")
        # 判断是否我创建的
        my_project_object = models.ProjectInfo.objects.filter(create_user=request.tracer.user,id=project_id).first()
        if my_project_object:
            # 是我创建的则让它通过，并将project对象写入request
            request.tracer.project = my_project_object
            return
        join_project_object = models.ParticipatorInfo.objects.filter(participator=request.tracer.user,project_id=project_id).first()
        if join_project_object:
            request.tracer.project = join_project_object.project
            print(request.tracer.project)
            return
        return redirect('project_list')
